package net.oschina.archx.spring.sequoiadb.factory;

import com.sequoiadb.base.Sequoiadb;
import net.oschina.archx.spring.sequoiadb.SequoiaFactory;
import net.oschina.archx.spring.sequoiadb.manager.SequoiaResourceManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert;

/**
 * SequoiaDB 默认工厂
 *
 * @author Archx
 */
public class DefaultSequoiaFactory implements SequoiaFactory, InitializingBean {

    private static ThreadLocal<Sequoiadb> context = new ThreadLocal<Sequoiadb>();

    private final Logger log = LoggerFactory.getLogger(getClass());

    private SequoiaResourceManager resourceManager;

    public DefaultSequoiaFactory() {
    }

    /**
     * 构造函数
     *
     * @param resourceManager 资源管理器
     */
    public DefaultSequoiaFactory(SequoiaResourceManager resourceManager) {
        Assert.notNull(resourceManager, "资源管理器不能为 NULL.");
        this.resourceManager = resourceManager;
    }

    public SequoiaResourceManager getResourceManager() {
        return resourceManager;
    }

    public void setResourceManager(SequoiaResourceManager resourceManager) {
        this.resourceManager = resourceManager;
    }

    @Override
    public Sequoiadb getInstance() throws InterruptedException {
        Sequoiadb conn = context.get();
        if (conn == null) {
            log.debug("线程池中不存在链接,将从资源管理器中获取一个链接.");
            conn = resourceManager.getConnection();
            context.set(conn);
        }
        return conn;
    }

    @Override
    public void close() {
        Sequoiadb conn = context.get();
        if (conn != null) {
            resourceManager.freeConnection(conn);
            log.debug("释放链接.");
        }
        context.remove();
        log.debug("移除线程池中的链接.");
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        //noinspection ConstantConditions
        if (resourceManager == null) {
            log.error("资源管理器 'resourceManager' 不能为 NULL.");
            throw new IllegalArgumentException("资源管理器不能为 NULL.");
        }

    }
}
